// cgjPlugin.js
const cgj = {
   // 节流函数
   throttle(func, wait) {
      let lastTime = 0;
      return function (...args) {
         const now = Date.now(); // 使用 Date.now() 而不是 new Date()
         if (now - lastTime >= wait) {
            lastTime = now;
            func.apply(this, args);
         }
      };
   },

   // 防抖函数
   debounce: function (func, wait) {
      let timeout;
      return function (...args) {
         clearTimeout(timeout);
         timeout = setTimeout(() => {
            func.apply(this, args);
         }, wait);
      };
   },
   // 格式化时间戳
   formatTimestamp: function (timestamp, format = "YYYY-MM-DD HH:mm:ss") {
      const isMilliseconds = timestamp.toString().length >= 13;
      const date = new Date(isMilliseconds ? timestamp : timestamp * 1000);

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      let formattedDate = format;
      formattedDate = formattedDate.replace("YYYY", year);
      formattedDate = formattedDate.replace("MM", month);
      formattedDate = formattedDate.replace("DD", day);
      formattedDate = formattedDate.replace("HH", hours);
      formattedDate = formattedDate.replace("mm", minutes);
      formattedDate = formattedDate.replace("ss", seconds);

      return formattedDate;
   },
   // 是否为空
   isNull: function (value) {
      if (
         value === null ||
         value === undefined ||
         value === "" ||
         (Array.isArray(value) && value.length === 0) ||
         (typeof value === "object" && Object.keys(value).length === 0)
      ) {
         return true;
      } 
      return false;
   },
   // 是否不为空
   isNotNull: function (value) {
      return !this.isNull(value);
   },
   // 下载文件
   download: async function (name, url) {
      return new Promise(async (resolve, reject) => {
         try {
            const fileExtension = url.split(".").pop();
            const response = await fetch(url, { mode: "no-cors" });
            if (!response.ok) {
               throw new Error(`网络请求失败: ${response.status} ${response.statusText}`);
            }
            const blob = await response.blob();
            const objectUrl = window.URL.createObjectURL(blob);

            const link = document.createElement("a");
            link.href = objectUrl;
            link.download = `${name}.${fileExtension}`;
            link.style.display = "none";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            window.URL.revokeObjectURL(objectUrl);

            resolve({ success: true, message: "文件下载成功" });
         } catch (error) {
            reject({ success: false, message: `文件下载失败: ${error.message}` });
         }
      });
   },
   // 找到顶层索引
   findTopLevelIndex: function (menuData, targetTitle) {
      let topLevelIndex = -1;

      const recursiveSearch = (data, parentIndex) => {
         for (let i = 0; i < data.length; i++) {
            const item = data[i];
            if (item.title === targetTitle) {
               topLevelIndex = parentIndex;
               return true;
            }
            if (item.children && item.children.length > 0) {
               if (recursiveSearch(item.children, parentIndex === -1 ? i : parentIndex)) {
                  return true;
               }
            }
         }
         return false;
      };

      recursiveSearch(menuData, -1);
      return topLevelIndex;
   },
};

export default {
   install: (app) => {
      app.config.globalProperties.$cgj = cgj;
      app.provide("cgj", cgj); // 提供全局属性
   },
};
